<!DOCTYPE HTML>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover">
    <title>Tonpay demo .</title>
    <body class="theme-dark" onload="init()">
        <h1>Jetton transfer demo</h1>
        <button onclick="transfer_jetton()">Jetton Transfer</button>
        <!-- Telegram -->
        <script src="https://telegram.org/js/telegram-web-app.js"></script>
        <script src="https://unpkg.com/@tonconnect/sdk@latest/dist/tonconnect-sdk.min.js"></script>
        <script src="https://bundle.run/buffer@6.0.3"></script>
        <script type="text/javascript">
            window.Buffer = window.Buffer??buffer.Buffer;
        </script>
        <script src="https://unpkg.com/@tonconnect/ui@2.0.0/dist/tonconnect-ui.min.js"></script>
        <script src="https://unpkg.com/tonweb@latest/dist/tonweb.js"></script>
        <script>
            var account;
            var tonConnectUI;
            async function ton_connect_ui_connect(url) {
                        try{
                if(!tonConnectUI)
                {
                    console.log("🚧 INIT the tonconnect ",tonConnectUI)
                    var manifest = 'https://test.tonspay.top/api/manifest' ;
                    if(url)
                    {
                        manifest +=`?url=${url}`
                    }
                    console.log(manifest)
                    tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
                    manifestUrl: manifest,
                    uiPreferences: {
                        theme: TON_CONNECT_UI.THEME.DARK,
                    },
                    });
                }
                }catch(e){console.error(e) ;}      
                    try{
                        if(tonConnectUI.connected)
                        {
                            console.log("Disconnect for connection reload")
                            await tonConnectUI.disconnect();
                        }
                    }catch(e){console.error(e) ;}      

                    try{
          await tonConnectUI.openModal();
  
          tonConnectUI.onStatusChange(
              walletAndwalletInfo => {
                  console.log("change : ", walletAndwalletInfo)
                  account = walletAndwalletInfo;
              }
          );
      }catch(e){console.error(e) ;}      
            }

            async function init() {
                await ton_connect_ui_connect()
            }
            async function transfer_jetton() {
                //USDT payment
                console.log("🚧 Jetton payment")
                const tonweb = new TonWeb();
                const jettonMinter = new TonWeb.token.jetton.JettonMinter(tonweb.provider, {address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs' /* USDT token address */});
                console.log(jettonMinter);
                const jettonMinterAddress = await jettonMinter.getJettonWalletAddress(new TonWeb.utils.Address(account.account.address));
                console.log(jettonMinterAddress.toString(true))
                const jettonWallet = new TonWeb.token.jetton.JettonWallet(tonweb.provider, {
                    address: jettonMinterAddress
                });
                const tonFee = '50000000' //多了就会自动退回的手续费

                const seqno = Date.now()
                const jettonBody = {
                    queryId: seqno,
                    jettonAmount: '10000',
                    toAddress: new TonWeb.utils.Address('UQADoX65_S5oswDkMY4rWv4iqv1aVHNMkE7aC5UabAkgl9aH' /* 收款地址，这是俺的地址*/),
                    responseAddress: new TonWeb.utils.Address(account.account.address)
                }

                console.log('🚧 jettonWallet.createTransferBody', jettonBody)
                let payload = await jettonWallet.createTransferBody(jettonBody)

                transaction = {
                    validUntil: Math.floor(Date.now() / 1000) + 6000, // 6000 秒
                    messages: [
                        {
                            address: jettonMinterAddress.toString(true),
                            amount: tonFee,
                            payload: TonWeb.utils.bytesToBase64(await payload.toBoc())
                        }
                    ]
                }
                try {
                    const result = await tonConnectUI.sendTransaction(transaction);
                    console.log("result : ", result)
                    // you can use signed boc to find the transaction
                    window.alert("pay success")
                    close_window_webapp()
                } catch (e) {
                    console.error(e);
                    window.alert(e)
                }

            }
        </script>
    </body>
</head>

</html>